<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/6/5
 * Time: 11:13
 */

namespace app\admin\controller\shop;

use app\admin\BaseController;
use app\admin\model\ProductCategoryRelation;
use app\admin\model\ProductGroupRelation;
use app\admin\model\ProductPrice;
use app\admin\model\Spec;
use app\admin\model\SpecCategoryRelation;
use app\admin\model\SpecItem;
use app\lib\exception\FailedException;
use app\lib\exception\NoJurisdiction;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\Validate\IdArrayMustPositive;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\ProductValidate;
use app\Validate\UIDValidate;
use think\Db;
use think\Exception;
use think\Request;
use app\admin\model\Product as ProductModel;

class Product extends BaseController {
    /**
     * [私有]复制地址
     * @param $file1
     * @param $file2
     * @return bool
     */
    private function copyFiles($file1,$file2){
        $contentx =@file_get_contents($file1);
        $openedfile = fopen($file2, "w");
        // http://www.manongjc.com/article/1350.html
        fwrite($openedfile, $contentx);
        fclose($openedfile);
        if ($contentx === FALSE) {
            $status=false;
        }else $status=true;
        return $status;
    }

    /**
     * 导入商品Excel
     * @throws FailedException
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function addExcel(){
        header('Access-Control-Allow-Origin:* ');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId, token");
        //防探针
        if(request()->isOptions()){
            return;
        }

        $file = request()->file('file');
        if ($file) {
            $info = $file->move('./uploads/exam');
            $path = '/home/wwwroot/api/public/uploads/exam/' . $info->getSaveName();   //正式环境
//            $path = 'D:/Web/oumaos/public/uploads/exam/' . $info->getSaveName();
//            $path = 'D:/phpStudy/PHPTutorial/WWW/oumaos/public/uploads/exam/' . $info->getSaveName();
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format
            $objPHPExcel = $objReader->load($path,$encode = 'utf-8');//$file_url即Excel文件的路径
            $drawing = new \PHPExcel_Writer_Excel2007_Drawing();
            $drawingHashTable = new \PHPExcel_HashTable();
            $drawingHashTable->addFromSource($drawing->allDrawings($objPHPExcel));

            $imageFilePath='./uploads/images/'.date('Y-m-d').'/';//路径-读文件
            $imageFilePath2='/uploads/images/'.date('Y-m-d').'/';//路径-存数据库用于访问
            if (! file_exists ( $imageFilePath )) { mkdir("$imageFilePath", 0777, true); }
            /*遍历单元格处理图片*/
            for ($i = 0; $i < $drawingHashTable->count(); $i++){
                $memoryDrawing = $drawingHashTable->getByIndex($i);
                if ($memoryDrawing instanceof \PHPExcel_Worksheet_Drawing)
                {
                    $filename = $memoryDrawing->getPath();
                    /*图片路径*/
                    $path_f = $imageFilePath. $memoryDrawing->getIndexedFilename();  //路径-读文件
                    $path_f2 = $imageFilePath2. $memoryDrawing->getIndexedFilename();//路径-存数据库用于访问
                    /*自定义函数*/
                    $this->copyFiles($filename, $path_f);
                    /*获取单元格的值*/
                    $cell = $memoryDrawing->getWorksheet()->getCell($memoryDrawing->getCoordinates());
                    /* 将该单元格的值设置为单元格的文本加上图片的 img 标签*/
                    $cell->setValue($cell->getValue() . $path_f2);
                }
            }

            $data = $objPHPExcel->getSheet(0)->toArray();//转换为数组格式
            $product_model = new \app\admin\model\Product();

            //提示信息：
            $str = "";

            try{
                //开始导入数据
                Db::startTrans();
                foreach($data as $k=>$v){
                    //跳过前四行说明
                    if($k<4){ continue; }

                    //[暂未添加]验重复 uid + 国际编码 + 规格描述  三者相同则为重复,自动记录并跳过,导入成功后,弹出提示
//                    $v[0],//国际编码,
//                    $v[2],//商家ID
//                    $v[6],//规格描述

                    //处理多张图片
                    $img_path = [];
                    if($v[22] != null){ array_push($img_path,$v[21]);}
                    if($v[23] != null){ array_push($img_path,$v[22]);}
                    if($v[24] != null){ array_push($img_path,$v[23]);}
                    if($v[25] != null){ array_push($img_path,$v[24]);}
                    if($v[26] != null){ array_push($img_path,$v[25]);}
                    $imgPath = serializeMysql($img_path);
                    $product = [
                        'img_path' =>$imgPath,
                        'international_code' => $v[0],//国际编码
                        'cover_img' =>$v[1],//封面图
                        'uid' => $v[2],//商家ID
                        'product_name' =>$v[3],//商品名称
                        'brand_name' =>$v[4],//商品品牌
                        'my_code'   =>$v[5],//内部码,
                        'sku_remark'   =>$v[6],//规格描述
                        'keyword' =>$v[3].$v[4].$v[0],//关键字
                        'description' =>$v[8],//商品描述
                        'product_code' =>$product_model->createProductCode("WXJ"),
                        'minimum_price' => $v[26],//最低批发价格
                        'tax_price' => $v[27],//含税价格
                        'market_price' => $v[12],//市场零售价格-市场指导价
                        'unit' => $v[28],//计量单位
                        'unit_number' => $v[29],//规格箱数
                        'guarantee_day' => $v[30],//保质天数
                        'one_weight' => $v[31],//单品重量
                        'fcl_weight' => $v[32],//整箱重量
                        'fcl_volume' => $v[33],//整箱体积
                        'fcl_code' =>$v[34],//整箱规格码
                        'product_price_one'=>$v[13], //单价-零售价
                        'invite_price'=>$v[20] //返现佣金
                    ];

                    //处理商品分组
                    //查询商品分组,若分组不存在,则新建分组
                    $dataInfo["group_id"][0] = $product_model->getGroupIdByName(strval($v["8"]),$v[2]);

                    //处理商品分类
                    $dataInfo['category_id'][0] = strval($v["9"]);
                    $dataInfo['category_id'][1] = strval($v["10"]);
                    $dataInfo['category_id'][2] = strval($v["11"]);

                    //批发价格处理
                    $product_price = [];

                    $price['type'] = 1; //小批
                    $price["price"] = $v[14];
                    $price['min_number'] = $v[15];
                    $price['max_number'] = $v[16];
                    array_push($product_price,$price);

                    $price['type'] = 2; //中批
                    $price["price"] = $v[17];
                    $price['min_number'] = $v[18];
                    $price['max_number'] = $v[19];
                    array_push($product_price,$price);

                    //商品基本属性添加
                    $product_id = $product_model->dataUpdate($product);
                    if(!$product_id){
                        Db::rollback();
                        throw new FailedException(['msg' => $k.'行商品属性添加失败']);
                    }
                    //商品分类添加
                    $res  = $product_model->productCategory($product_id,$dataInfo);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException([
                            'msg' => $k.'行商品分类处理失败'
                        ]);
                    }
                    //商品分组添加
                    $res  = $product_model->productGroup($product_id,$dataInfo);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException([
                            'msg' => $k.'行商品分组处理失败'
                        ]);
                    }
                    //处理批发价格
                    $res = $product_model->productPrice($product_id,$product_price,$v[2]);
                    if(!$res){
                        Db::rollback();
                        throw new FailedException([
                            'msg' => $k.'行商品价格处理失败'
                        ]);
                    }
                }
                //结束导入数据
                Db::commit();
                return ajax_return('1','导入成功');
            }catch (Exception $exception){
                Db::rollback();
                throw new FailedException([
                    'msg' => "出现问题,导入失败请联系开发人员,错误提示:".$exception->getMessage()
                ]);
            }
        }
    }

    /**
     * 添加商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NoJurisdiction
     * @throws ParameterException
     */
    public function createProduct(Request $request){
        (new ProductValidate()) ->goCheck();
        $info = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==2){//如果是商家账号
            if($info['uid'] != $admin['uid']){ throw new NoJurisdiction();}
        }
        $imgPath = serializeMysql($info['img_path']);
        $product_model = new \app\admin\model\Product();
        $product = [
            'img_path' =>$imgPath,
            'uid' => $info['uid'],//商家ID
            'product_name' =>$info['product_name'],//商品名称
            'brand_name' =>$info['brand_name'],//商品品牌
            'international_code' => $info['international_code'],//国际编码
            'my_code'            => $info['my_code'],
            'cover_img' =>$info['cover_img'],//封面图
            'keyword' =>$info['product_name'].$info['brand_name'].$info['international_code'],//关键字
            'description' =>htmlspecialchars_decode($info['description']),//商品描述
            'product_code' =>$product_model->createProductCode("WXJ"),
            'minimum_price' => $info['minimum_price'],//最低批发价格
            'tax_price' => $info['tax_price'],//含税价格
            'market_price' => $info['market_price'],//市场零售价格-市场指导价
            'unit' => $info['unit'],//计量单位
            'unit_number' => $info['unit_number'],//规格箱数
            'guarantee_day' => $info['guarantee_day'],//保质天数
            'one_weight' => $info['one_weight'],//单品重量
            'fcl_weight' => $info['fcl_weight'],//整箱重量
            'fcl_volume' => $info['fcl_volume'],//整箱体积
            'fcl_code' =>$info['fcl_code'],//整箱规格码
            'product_price_one'=>$info['product_price_one'], //单价-销售价
            'sku_remark'   =>$info["sku_remark"], //规格描述
            'invite_price'=>$info["invite_price"] //返现佣金
        ];

        try{
            //商品基本属性添加
            Db::startTrans();
            $product_id = $product_model->dataUpdate($product);
            if(!$product_id){
                Db::rollback();
                throw new FailedException(['msg' => '商品添加失败']);
            }
            //处理商品分类
            $res = $product_model->productCategory($product_id,$info);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品分类处理失败']);
            }
            //处理商品分组
            $res = $product_model->productGroup($product_id,$info);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品分组处理失败']);
            }
            //处理批发价格
            $res = $product_model->productPrice($product_id,$info["product_price"],$info["uid"]);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品价格处理失败']);
            }
            Db::commit();
            return writeJson(200,[],"操作成功");
        }catch (Exception $exception){
            Db::rollback();
            throw new FailedException([ 'msg' => $exception->getMessage()]);
        }
    }

    /**
     * 删除商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function deleteProduct(Request $request){
        $post = $request->post();
        $product_model = new \app\admin\model\Product();
        $res = $product_model->where([['id','in',$post['id']]])->update(['delete_time'=>time()]);
        if(!$res){ throw new FailedException(['msg' => '操作失败']); }
        return writeJson(200,[],"操作成功");
    }

    /**
     * 编辑商品
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NoJurisdiction
     * @throws ParameterException
     */
    public function editProduct(Request $request){
        (new ProductValidate()) ->goCheck();
        (new IdMustPositive())  ->goCheck();
        $info = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==2){ //如果是商家账号
            if($info['uid'] != $admin['uid']){ throw new NoJurisdiction(); }
        }
        $imgPath = serializeMysql($info['img_path']);
        $product_model = new \app\admin\model\Product();
        $product = [
            'id'       =>$info['id'],
            'img_path' =>$imgPath,
            'product_name' =>$info['product_name'],//商品名称
            'brand_name' =>$info['brand_name'],//商品品牌
            'international_code' => $info['international_code'],//国际编码
            'my_code'            =>$info['my_code'],//内部码
            'cover_img' =>$info['cover_img'],//封面图
            'minimum_price' => $info['minimum_price'],//最低批发价格
            'tax_price' => $info['tax_price'],//含税价格
            'market_price' => $info['market_price'],//市场零售价格
            'unit' => $info['unit'],//计量单位
            'unit_number' => $info['unit_number'],//规格箱数
            'guarantee_day' => $info['guarantee_day'],//保质天数
            'one_weight' => $info['one_weight'],//单品重量
            'fcl_weight' => $info['fcl_weight'],//整箱重量
            'fcl_volume' => $info['fcl_volume'],//整箱体积
            'fcl_code' =>$info['fcl_code'],//整箱规格码
            'keyword' =>$info['product_name'].$info['brand_name'].$info['international_code'],//关键字
            'description' =>htmlspecialchars_decode($info['description']),//商品描述
            'product_code' =>$product_model->createProductCode("WXJ"),
            'product_price_one' =>$info['product_price_one'],//平台零售价
            'sku_remark'   =>$info["sku_remark"], //规格描述
            'invite_price'=>$info["invite_price"] //返现佣金
        ];

        try{
            Db::startTrans();
            $product_id = (new ProductModel())->dataUpdate($product);
            if(!$product_id){
                Db::rollback();
                throw new FailedException(['msg' => '商品添加失败']);
            }
            //处理商品分类
            $res  = $product_model->productCategory($product_id,$info);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品分类处理失败']);
            }
            //处理商品分组
            $res  = $product_model->productGroup($product_id,$info);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品分组处理失败']);
            }
            //处理批发价格
            $res = $product_model->productPrice($product_id,$info["product_price"],$info["uid"]);
            if(!$res){
                Db::rollback();
                throw new FailedException(['msg' => '商品价格处理失败']);
            }
            Db::commit();
            return writeJson(200,[],"操作成功");
        }catch (\Exception $exception){
            Db::rollback();
            throw new FailedException(['msg' => $exception->getMessage()]);
        }
    }

    /**
     * 查看商品详情
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     * @throws NotFoundException
     */
    public function detailProduct(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $detail = (new \app\admin\model\Product())->findOne([['id','eq',$post['id']]]);
        if(!$detail){
            throw new NotFoundException(['msg'=>'商品不存在']);
        }
        $detail = $detail->toArray();
        $detail['cover_img'] = imgUrlToAbsolute($detail['cover_img']);
        $detail['img_path']  = serializeMysql($detail['img_path'],1);
        foreach ($detail['img_path'] as &$value){
            $value = imgUrlToAbsolute($value);
        }
        $detail['description'] = html_entity_decode($detail['description']);
        $detail['product_price'] = (new ProductPrice())->selectList([['product_id','eq',$post['id']]],"id,uid,product_id,type,price,min_number,max_number");
        $detail['category_id'] = (new ProductCategoryRelation())->where('product_id',$post['id'])->column("category_id");
        $detail['group_id'] = (new ProductGroupRelation())->where('product_id',$post['id'])->column("group_id");
        return writeJson(200,['detail'=>$detail]);
    }

    /**
     * 商家下的商品列表
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function productList(Request $request){
        (new PageMustValidate()) ->goCheck();
        $post = $request->post();
        $admin = $this->admin;

        $where =[];
        $where1=[];
        if($admin['uid']!=0){
            $where[] = ['om_product.uid','eq',$admin['uid']];
        }else if($post['uid'] != 0){
            $where[] = ['om_product.uid','eq',$post['uid']];
        }

        $where = addWhere($post,['international_code'=>"",],$where,2,"om_product.");//国际编码
        $where = addWhere($post,['is_publish'=>"",],$where,1,"om_product.");//发布状态
        $where1 = addWhere($post,['name'=>""],$where1,2);//商家名称
        $where1 = addWhere($post,['type'=>""],$where1,1);//商家类型

        if(isset($post['category_id'])&&!empty($post['category_id'])){//商家分类的id
            //通过三级分类的id  查询商品
            $product_id = (new ProductCategoryRelation())->where("category_id",'eq',$post['category_id'])->column("product_id");
            $where[] = [
              'om_product.id','in',$product_id
            ];
        }
        $count = (new \app\admin\model\Product())->getCountHasWhere("shop",$where,$where1);
        $where['page'] = $post['page'];
        $list =  (new \app\admin\model\Product())->wechatListHasWhere("shop",$where,$where1,"om_product.*","om_product.id desc",$post['page_number']);

        foreach ($list as $key=>$value){
            $list[$key]['stock'] = (new \app\api\model\Product())->getProductStock($value['id'],$value['shop']['type'],$value['uid']);
            $list[$key]['price'] = (new ProductPrice())->findOne([['product_id','eq',$value['id']],['type','eq',1]],'price');
        }
        return writeJson(200,['list'=>$list,'count'=>$count]);
    }

    /**
     * 商家后台下的商品列表
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     * @throws \think\exception\DbException
     */
    public function onLineProductList(Request $request){
        //验证是否传了商家的id
        (new PageMustValidate()) ->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        if($admin['account_type']!=2){ throw new FailedException(['msg'=>'不属于商家账号']); }

        $where = [];
        if(isset($post['storageType'])){//1是展示中 2是已入库 3是未入库
            if($post['storageType']==1){//展示中
                $where = ['a.is_publish','eq',2];
            }elseif ($post['searchType']==2){//已入库

            }else{
                $where[] =['b.id','eq',0]; //未入库
            }
        }

        $where[] = ['a.uid','eq',$admin['uid']];//商家的id
        if(isset($post['group_id'])&&!empty($post['group_id'])){
            $group = (new ProductGroupRelation())->where("group_id",'eq',$post['group_id'])->column("product_id");
            $where[] = ['a.id','in',$group];
        }
        $field = "a.id,a.sales_actual_number,a.create_time,a.cover_img,a.product_name,a.visitor_number,a.hot_number,a.is_publish,a.sort,c.price,ifNull(`b`.`stock`, 0) as stock";
        $dataList = (new \app\admin\model\Product())
            ->alias("a")
            ->join("(select product_id,sum(stock) as stock from om_warehouse_general group by product_id) b","a.id = b.product_id ","left")
            ->join("om_product_price c","a.id = c.product_id and c.type = 1 and c.delete_time is null","left")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);
        $dataList=$dataList->toArray();

        $count  = $dataList['total'];
        $dataList = $dataList['data'];
        foreach ($dataList as $key=>$value){
            $dataList[$key]['cover_img'] = imgUrlToAbsolute($value['cover_img']);
        }
        $returnList = [
            'count'=>$count,
            'dataList'=>$dataList
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 通过商品分类查询 分类下面的属性集和属性值
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function categorySpec(Request $request){
        $post = $request->post();
        if(!isset($post['category_id'])||count($post['category_id'])==0){
            throw new FailedException([
                'msg' => '请先选择分类'
            ]);
        }
        $specIdList = (new SpecCategoryRelation())->where('category_id','in',$post['category_id'])->group("spec_id")->column("spec_id");
        $specList =  (new Spec())->selectList([['id','in',$specIdList]],"id,spec_id,spec_title","sort desc");
        $specList = $specList->toArray();
        $specId = array_column($specList,"spec_id");
        $specItemList =  (new SpecItem())->selectList([['spec_id','in',$specId]],"id,spec_id,spec_item_id,spec_item_value");
        $specItemList = $specItemList->toArray();
        $specList = arrayLevel($specList, $specItemList,"spec_id");
        return writeJson(200,['specList'=>$specList]);
    }

    /**
     * 商品的上下架
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function productIsPublish(Request $request){
        (new IdArrayMustPositive())->goCheck();
        $post = $request->post();
        $where = [['id','in',$post['id']],];
        $res = (new \app\admin\model\Product())->where($where)->setField("is_publish",$post['is_publish']);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200,[],'操作成功');
    }

    /**
     * 商品改分组
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function productChangeGroup(Request $request){
        (new IdArrayMustPositive())->goCheck();
        $post = $request->post();
        if(!isset($post['group_id'])){
            throw new ParameterException(['msg'=>'缺少分组id']);
        }

        Db::startTrans();
        //改分组先将之前的分组全部删掉
        (new ProductGroupRelation())->where('product_id','in',$post['id'])->delete();
        $list = [];
        foreach ($post['id'] as $value){
            $list[] = [
              'product_id'=>$value,
              'group_id' =>$post['group_id']
            ];
        }
        $res = (new ProductGroupRelation())->saveAll($list);
        if(!$res){
            Db::rollback();
            throw new FailedException(['msg'=>'操作失败']);
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 通过条件搜索出一条商品
     * international_code 国际编码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws NotFoundException
     */
    public function searchProduct(Request $request){
        $post = $request->post();
        $where =[];
        $where = addWhere($post,['international_code'=>''],$where,1);
        $where[] = ['b.type','eq',3];
        $field = "a.id,a.cover_img,a.product_name,d.price";
        $product = (new \app\admin\model\Product())
            ->alias("a")
            ->join("om_product_price d","a.id = d.product_id and d.type = 1","right")
            ->join("om_shop b","a.uid = b.id and b.status = 2 and b.use_status = 1","right")
            ->field($field)
            ->where($where)
            ->find();
        if(!$product){
            throw new NotFoundException(['msg'=>'商品不存在']);
        }
        $product['cover_img'] = imgUrlToAbsolute($product['cover_img']);
        return writeJson(200,['product'=>$product]);
    }

    /**
     * 通过条件搜索出某商家下的多条商品
     * international_code 国际编码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws NoJurisdiction
     * @throws ParameterException
     */
    public function searchUIDProduct(Request $request){
        (new UIDValidate())->goCheck();
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        $where =[];
        if($admin['account_type']==2){//如果是商家账号
            if($post['uid']!=$admin['uid']){ throw new NoJurisdiction(); }
            $where[] = ['a.uid','eq',$post['uid']];
        }
        else{
            $where[] =['a.uid','eq',$post['uid']];
        }
        if(isset($post["international_code"])){
            $where[] = [ 'a.international_code','like','%'.$post['international_code'].'%'];
        }
        if(isset($post["product_name"])){
            $where[] = [ 'a.product_name','like','%'.$post['product_name'].'%'];
        }
        $count =  (new \app\admin\model\Product()) ->alias("a")
            ->join("om_warehouse_general c","a.id = c.product_id and c.warehouse_id = 1","left")
            ->join("om_product_price d","a.id = d.product_id and d.type = 1 and d.delete_time is null","left")
            ->join("om_shop e","a.uid = e.id","left")
            ->where($where)->count();
        $field = "a.id,a.cover_img,a.product_name,a.international_code,a.sku_remark as sku,c.stock warehouse_stock,d.price,e.name as shop_name";
        $product = (new \app\admin\model\Product())
            ->alias("a")
            ->join("om_warehouse_general c","a.id = c.product_id and c.warehouse_id = 1","left")
            ->join("om_product_price d","a.id = d.product_id and d.type = 1 and d.delete_time is null","left")
            ->join("om_shop e","a.uid = e.id","left")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'], false, [
                'page' => $post['page']])->each(function ($item){
                    $item['cover_img'] = imgUrlToAbsolute($item['cover_img']);
                    if(empty($item['warehouse_stock'])){
                        $item['warehouse_stock'] ="-";
                    }
                    return $item;
            });
        return writeJson(200,['dataList'=>$product,'count'=>$count]);
    }
}